import Vue from 'vue'
import Router from 'vue-router'

Vue.use(Router)

/* Layout */
import Layout from '@/layout'
import LayoutWithoutMenu from '@/layout/view'
import {getUser} from '@/utils/auth' // get token from cookie
/**
 * Note: sub-menu only appear when route children.length >= 1
 * Detail see: https://panjiachen.github.io/vue-element-admin-site/guide/essentials/router-and-nav.html
 *
 * hidden: true                   if set true, item will not show in the sidebar(default is false)
 * alwaysShow: true               if set true, will always show the root menu
 *                                if not set alwaysShow, when item has more than one children route,
 *                                it will becomes nested mode, otherwise not show the root menu
 * redirect: noRedirect           if set noRedirect will no redirect in the breadcrumb
 * name:'router-name'             the name is used by <keep-alive> (must set!!!)
 * meta : {
    roles: ['admin','editor']    control the page roles (you can set multiple roles)
    title: 'title'               the name show in sidebar and breadcrumb (recommend set)
    icon: 'svg-name'             the icon show in the sidebar
    breadcrumb: false            if set false, the item will hidden in breadcrumb(default is true)
    activeMenu: '/example/list'  if set path, the sidebar will highlight the path you set
  }
 */

/**
 * constantRoutes
 * a base page that does not have permission requirements
 * all roles can be accessed
 */
export const constantRoutes = [
  // {
  //   path: '/redirect',
  //   component: Layout,
  //   hidden: true,
  //   children: [
  //     {
  //       path: '/redirect/:path(.*)',
  //       component: () => import('@/views/redirect/index')
  //     }
  //   ]
  // },
  {
    path: '/login',
    component: () => import('@/views/login/index'),
    hidden: true
  },

  {
    path: '/404',
    component: () => import('@/views/404'),
    hidden: true
  },
  // {
  //   path: '/',
  //   component: Layout,
  //   redirect: '/home',
  //   name: '统计',
  //   // meta: {title: '统计', icon: 'dashboard', affix: true},
  //   children: [
  //     {
  //       path: 'home',
  //       name: 'home',
  //       permission: ['superManager'],
  //       component: () => import('@/views/dashboard/home'),
  //       meta: {title: '统计', icon: '', affix: true}
  //     }
  //   ]
  // },


  // 404 page must be placed at the end !!!
  {path: '*', redirect: '/404', hidden: true}
]

export const asyncRouterMap = [
  {
    path: '/',
    component: Layout,
    redirect: '/home',
    name: '统计分析',
    // meta: {title: '统计', icon: 'dashboard', affix: true},
    children: [
      {
        path: 'home',
        name: 'home',
        permission: ['superManager', '统计分析(区域查看)'],
        component: () => import('@/views/dashboard/home'),
        meta: {title: '统计分析', icon: '', affix: true}
      }
    ]
  },
  {
    path: '/project',
    component: Layout,
    redirect: '/project',
    name: '项目策划',
    meta: {title: '项目策划', icon: ''},
    children: [
      {
        path: 'project',
        name: 'project',
        permission: ['superManager', "项目查看"],
        component: () => import('@/views/project/project'),
        meta: {title: '项目策划', icon: ''}
      }
    ]
  },
  {
    path: '/system',
    component: Layout,
    redirect: '/system',
    name: '系统管理',
    meta: {title: '系统管理', icon: ''},
    children: [
      {
        path: 'user',
        name: '用户管理',
        permission: ['superManager', 'userReadAccess'],
        component: () => import('@/views/system/user'),
        meta: {title: '用户管理', icon: ''}
      },
      {
        path: 'role',
        name: '角色管理',
        permission: ['superManager', 'roleReadAccess'],
        component: () => import('@/views/system/role'),
        meta: {title: '角色管理', icon: 'tree'}
      },
      {
        path: 'access',
        name: '权限管理',
        permission: ['superManager'],
        component: () => import('@/views/system/access'),
        meta: {title: '权限管理', icon: 'ic_permission'}
      },
      {
        path: 'company',
        name: 'company',
        permission: ['superManager'],
        component: () => import('@/views/project/company'),
        meta: {title: '公司管理列表', icon: ''}
      }
    ]
  }
]
export const asyncRoutes = asyncRouterMap;

/**路由是否已经添加过避免重复添加(只判断一级，因为二级的路径可能是重复的名称)*/
function isHadRouter(list, path) {
  for (let i = 0; i < list.length; i++) {
    if (path == list[i].path) {
      return true
    }
  }
  return false
}

/**循环对比是否有权限*/
function isHadPermission(userAccessList, needAccessList) {
  if (userAccessList == null || userAccessList == undefined
    || needAccessList == null || needAccessList == undefined) {
    return false
  }
  for (let i = 0; i < userAccessList.length; i++) {
    for (let j = 0; j < needAccessList.length; j++) {
      if (userAccessList[i] == needAccessList[j]) {
        return true
      }
    }
  }
  return false
}

/**权限过滤路由的表*/
export function filterRouter(list) {
  // console.log('开始过滤')
  const user = getUser()
  // console.log(list)
  // console.log(JSON.stringify(user))

  if (user != null) {
    for (let i = 0; i < list.length; i++) {
      if (list[i].children != null) {
        filterRouter(list[i].children)
      } else {
        const permissionList = list[i].permission
        if (!isHadPermission(user.accessList, permissionList)) {
          console.log(list[i].name + '无权限')
          list.splice(i--, 1)
        } else {
          console.log(list[i].name + '有权限')
        }
      }
    }
  }
  return list
}

/**过滤自动清除 component 和不需要的参数以节省存储空间*/
export function filterRouterData(list) {
  for (let i = 0; i < list.length; i++) {
    // console.log(list[i].name + '  ' + (list[i].redirect != null && list[i].redirect != ''))
    if (list[i].redirect != null && list[i].redirect != '' && (list[i].children == null || list[i].children.length == 0)) {//根据redirect判断是否是一级的菜单
      // console.log('剔除的菜单' + list[i].name)
      list.splice(i--, 1)
    }
  }
  for (let i = 0; i < list.length; i++) {
    Vue.delete(list[i], 'component')
    // Vue.delete(list[i], 'redirect')
    // Vue.delete(list[i], 'name')
    if (list[i].children != null) {
      filterRouterData(list[i].children)
    }
  }
  return list
}

/**过滤路由的表*/
export function createRouter() {
  const list = []

  for (let i = 0; i < constantRoutes.length; i++) {//装载全部静态路由
    list.push(constantRoutes[i])
  }
  for (let i = 0; i < asyncRouterMap.length; i++) {
    if (!isHadRouter(list, asyncRouterMap[i].path)) {//装载全部动态路由
      list.push(asyncRouterMap[i])
    }
  }
  console.log('装载的路由')
  console.log(list)
  return new Router({
    // mode: 'history', // require service support
    scrollBehavior: () => ({y: 0}),
    routes: list
  })
}

const createRouter2 = () => new Router({
  // mode: 'history', // require service support
  scrollBehavior: () => ({y: 0}),
  routes: constantRoutes
})

const router = createRouter()

// Detail see: https://github.com/vuejs/vue-router/issues/1234#issuecomment-357941465
export function resetRouter() {
  const newRouter = createRouter()
  router.matcher = newRouter.matcher // reset router
}

export default router
